import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.*;
import java.util.Calendar;
import java.util.Random;

import javax.sql.*;

public class SpatialTest {

	static boolean IS_MYSQL_INSERT=false;//false means POSTGRES insert.
	
	// MySQL
	//static String dbUrl = "jdbc:mysql://localhost:3306/test?";
	//static String dbClass = "com.mysql.jdbc.Driver";
	//static String schemaPrefix="test."

	// PostGres
	static String dbUrl = "jdbc:postgresql://localhost:5432/postgis?";
	static String dbClass = "org.postgresql.Driver";
	static String schemaPrefix="";
	
	static String DB_USERNAME="postgres";//root/postgres
	static String DB_PASSWD="pass";
	
	public static void main(String args[]) {
		
		insertGeoData();

	} // end main

	public static void findGeoLocationsInRadius()
	{
		
	}
	
	public static void insertGeoData()
	{
		try {

			Class.forName(dbClass);

			Connection con = DriverManager.getConnection(dbUrl, DB_USERNAME, DB_PASSWD);
			// Connection con = DriverManager.getConnection
			// (dbUrl,"postgres","pass");
			Statement stmt = con.createStatement();

			String query1;
			long startTime = Calendar.getInstance().getTimeInMillis();
			//TODO: Randomize the lat, long inputs
			Random rand = new Random();
			
			String geomFunc="";
			if (IS_MYSQL_INSERT)
				geomFunc="GeomFromText";
			else
				geomFunc="st_pointfromtext";//PostGres
				
			for (int i = 0; i < 1000; i++) {				
				
				double lat = rand.nextDouble() * 180 - 90;
				BigDecimal bd1 = new BigDecimal(lat).setScale(2, RoundingMode.HALF_EVEN); 
				lat = bd1.doubleValue(); 
				
				double lon = rand.nextDouble() * 360 - 180;
				BigDecimal bd = new BigDecimal(lon).setScale(2, RoundingMode.HALF_EVEN); 
				lon = bd.doubleValue(); 
				
				query1 = "INSERT INTO " + schemaPrefix + "geocode(latitude, longitude, location) VALUES (" + lat + "," + lon + ", " + geomFunc + "('POINT(" + lat + " " + lon + ")') )";
				System.out.println(query1);
				int res = stmt.executeUpdate(query1);
				// System.out.println("res: " + res);
			}

			long timeTaken = Calendar.getInstance().getTimeInMillis()
					- startTime;
			System.out.println("Time Taken: " + timeTaken);

			con.close();
		} // end try

		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	
} // end class
